using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace HHHFramework {
    public class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
    {
        private static T instance = null;
        public static T Instance
        {

            get
            {
                if (instance == null)
                {

                    instance = FindObjectOfType<T>();

                    if (FindObjectsOfType<T>().Length > 1)
                    {
                        Debug.LogError("More than 1!");
                        return instance;
                    }

                    if (instance == null)
                    {
                        Debug.Log(typeof(T).Name + "不存在  创建中");
                        string instanceName = typeof(T).Name;
                        GameObject instanceGO = GameObject.Find(instanceName);

                        if (instanceGO == null)
                            instanceGO = new GameObject(instanceName);

                        instance = instanceGO.AddComponent<T>();
                        //DontDestroyOnLoad(instanceGO);  //保证实例不会被释放
                        Debug.Log("Add New Singleton " + instance.name + " in Game!");
                    }
                    else
                    {
                        Debug.Log("Already exist: " + instance.name);
                    }
                }

                return instance;
            }

            private set
            { }

        }

        protected virtual void OnDestory()
        {
            instance = null;
        }
    }
}

